package com.ycsj.goldmedalnewconcept.activity;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.squareup.picasso.Picasso;
import com.ycsj.goldmedalnewconcept.ButtonActivity;
import com.ycsj.goldmedalnewconcept.adapter.ListViewAdapter;
import com.ycsj.goldmedalnewconcept.bean.AttResponse;
import com.ycsj.goldmedalnewconcept.bean.HomeworkResponse;
import com.ycsj.goldmedalnewconcept.bean.LoginResponse;
import com.ycsj.goldmedalnewconcept.bean.ScoreThemeResponse;
import com.ycsj.goldmedalnewconcept.bean.StudentInfo;
import com.ycsj.goldmedalnewconcept.bean.StudentInfoResponse;
import com.ycsj.goldmedalnewconcept.bean.ScoreThemeResponse.ScoreTheme;
import com.ycsj.goldmedalnewconcept.constant.Constant;
import com.ycsj.goldmedalnewconcept.utils.SPUtil;
import com.ycsj.goldmedalnewconcept.R;

//测试主题（学生列表）
public class ScoreThemeActivity extends Activity implements OnClickListener {
	
	private ImageView iv_back;
	private TextView tv_title;
	private TextView tv_mod;
	private GridView gv_student;
	private String userclass;
	private String rowid;
	private String tag;
	private String input;
	private String account;
	private String role;
	private Intent intent;
	private Handler handler;
	private HomeworkAdapter mAdapter;
//	private List<StudentInfo> list;
	private List<ScoreTheme> scorelist;
	private String num;
	private String team;
	
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_scoretheme);
		intent = getIntent();
		userclass = intent.getStringExtra("userclass");
		rowid = intent.getStringExtra("rowid");
		tag = intent.getStringExtra("tag");
		num = intent.getStringExtra("num");
		team = intent.getStringExtra("team");
		
		
		account = SPUtil.getString(this, "account", "");
		role = SPUtil.getString(this, "role", "");
		Log.e("test", userclass+"userclass");
		Log.e("test", rowid+"rowid");
		Log.e("test", tag+"tag");
		Log.e("test", num+"num");
		
		handler = new MyHandler();
		
		initView();
//		initStudent();
		initData();
		setOnListener();
	}
//http://192.168.0.198:8888/ycsj_platform/ManageMsg?type=39&c=18271261779&role=0&userclass=2722&teachermobile=13006314760&tagid=22

	private void initView() {
		iv_back = (ImageView) findViewById(R.id.iv_back);
		gv_student = (GridView) findViewById(R.id.gv_student);
		tv_title = (TextView) findViewById(R.id.tv_title);
		tv_mod = (TextView) findViewById(R.id.tv_mod);
		if(tag!=null){
			tv_title.setText(tag);
		}
	}
	
	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		initData();
		
		super.onRestart();
	}
	
	
	private void initStudent() {
		OkHttpClient mOkHttpClient = new OkHttpClient();
//		mOkHttpClient.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
		FormEncodingBuilder builder = new FormEncodingBuilder();
		builder.add("type", "2");
		builder.add("ttel", account);
		builder.add("num", num);
		builder.add("platform", "2");
//		http://192.168.0.164:8080/ycsj_count/MessageCenter?type=2&ttel=13006314760&num=1&platform=2
//		http://pm.moregolden.com/ycsj_count/MessageCenter?type=2&ttel=18672626702&num=1&platform=2
		Request request = new Request.Builder()
				.url(Constant.ycsj_count_MessageCenter)
				.post(builder.build()).build();
		mOkHttpClient.newCall(request).enqueue(new Callback() {
				
			@Override		
			public void onFailure(Request arg0, IOException arg1) {
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						Toast.makeText(getBaseContext(), "网络无响应，请检查网络连接", 0)
								.show();
					}
				});
			}
 
			@Override
			public void onResponse(Response arg0) throws IOException {
				// 解析Json数据，保存登录状态及身份信息
				
				Gson gson = new Gson();
				String json1 = arg0.body().string();
				StudentInfoResponse fromJson = gson.fromJson(
						json1, StudentInfoResponse.class);
				Log.e("teststu", json1);
//				list = fromJson.list;
//				initData();
//				Message message = Message.obtain();
//				message.arg1 = 0;
//				message.obj = fromJson;
//				handler.sendMessage(message);
			}
		});
	}
	
	private void initData() {
		OkHttpClient mOkHttpClient = new OkHttpClient();
//		mOkHttpClient.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
		FormEncodingBuilder builder = new FormEncodingBuilder();
		builder.add("type", "38");
		builder.add("c", account);
		builder.add("role", role);
		builder.add("userclass", userclass);
		builder.add("schoolid", "0");
		builder.add("tagid", rowid);
		Request request = new Request.Builder()
				.url(Constant.SERVER_LOC + "ManageMsg")
				.post(builder.build()).build();
		mOkHttpClient.newCall(request).enqueue(new Callback() {
//http://192.168.0.198:8888/ycsj_platform/ManageMsg?type=38&c=13006314760&role=2&userclass=2722&schoolid=0&tagid=22
			
			
			@Override		
			public void onFailure(Request arg0, IOException arg1) {
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						Toast.makeText(getBaseContext(), "网络无响应，请检查网络连接", 0)
								.show();
					}
				});
			}
 
			@Override
			public void onResponse(Response arg0) throws IOException {
				// 解析Json数据，保存登录状态及身份信息

				Gson gson = new Gson();
				String json = arg0.body().string();
				Log.e("test", json);
				ScoreThemeResponse fromJson = gson.fromJson(
						json, ScoreThemeResponse.class);
//				 
				scorelist = fromJson.list;
				Message message = Message.obtain();
				message.arg1 = 0;
				message.obj = fromJson;
				handler.sendMessage(message);
			}
		});
	}
	
	public class MyHandler extends Handler {
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			ScoreThemeResponse fromJson = (ScoreThemeResponse) msg.obj;
			if(fromJson==null){
				Toast.makeText(getApplicationContext(), "错误，请检查网络是否正常", 0)
				.show();
				return;
			}
			
			if("1".equals(fromJson.state)){
				mAdapter =new HomeworkAdapter();
				gv_student.setAdapter(mAdapter);
				gv_student.setOnItemClickListener(new OnItemClickListener() {

					

					@Override
					public void onItemClick(AdapterView<?> parent, View view,
							int position, long id) {
						// TODO Auto-generated method stub
						
						if("1".equals(scorelist.get(position).score_status)){
							Intent intent = new Intent(ScoreThemeActivity.this, ScoreDetailActivity.class);
							intent.putExtra("name", scorelist.get(position).name);
							intent.putExtra("tagid", rowid);
							intent.putExtra("userclass", userclass);
							intent.putExtra("userid", scorelist.get(position).sttel);
							startActivity(intent);
							
						}else if("0".equals(scorelist.get(position).score_status)){
						Intent intent = new Intent(ScoreThemeActivity.this, AddScoreActivity.class);
						intent.putExtra("name", scorelist.get(position).name);
						intent.putExtra("tagid", rowid);
						intent.putExtra("userclass", userclass);
						intent.putExtra("userid", scorelist.get(position).sttel);
						startActivity(intent);
						}
					}
				});
				
			}else{
				Toast.makeText(getApplicationContext(), "请检查网络是否正常", 0)
				.show();
			}
		}
	}
	
	public class MyHandler1 extends Handler {
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			StudentInfoResponse fromJson = (StudentInfoResponse) msg.obj;
			if(fromJson==null){
				Toast.makeText(getApplicationContext(), "错误，请检查网络是否正常", 0)
				.show();
				return;
			}
			
			
		}
	}
	
	class HomeworkAdapter extends BaseAdapter {
		private LayoutInflater inflater= LayoutInflater.from(getBaseContext());

		

		@Override
		public int getCount() {
			if (null != scorelist) {
				return scorelist.size();
			} else {
				return 0;
			}
		}

		@Override
		public Object getItem(int position) {
			return scorelist.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder viewHolder;
			if (convertView == null) {
				convertView = inflater.inflate(R.layout.gv_item_scorestudent, null);
				viewHolder = new ViewHolder();
				viewHolder.title = (TextView) convertView
						.findViewById(R.id.title);
				viewHolder.tv_score = (TextView) convertView
						.findViewById(R.id.tv_score);
				viewHolder.root = (LinearLayout) convertView
						.findViewById(R.id.root);
				viewHolder.image = (ImageView) convertView
						.findViewById(R.id.image);
				convertView.setTag(viewHolder);
			} else {
				viewHolder = (ViewHolder) convertView.getTag();
			}
			viewHolder.title.setText(scorelist.get(position).name);
			Picasso.with(getBaseContext()).load(scorelist.get(position)
					.icon).error(R.drawable.header).into(viewHolder.image);	
			if("1".equals(scorelist.get(position).score_status)){
				viewHolder.tv_score.setText(scorelist.get(position).score+"分");
				viewHolder.root.setBackgroundResource(R.drawable.shape_gary);
			}
			if("0".equals(scorelist.get(position).score_status)){
				viewHolder.tv_score.setText("");
				viewHolder.root.setBackgroundResource(R.color.transparent);
			}
			
			
			return convertView;
		}
	}
	
	class ViewHolder {
		public TextView title;
		public TextView tv_score;
		public ImageView image;
		public LinearLayout root;
	}
	
	private void setOnListener() {
		iv_back.setOnClickListener(this);
		tv_mod.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.iv_back:
			finish();
			break;
		case R.id.tv_mod:
			
			final EditText et = new EditText(this);  
		    et.setBackgroundResource(R.color.white);
            
		    new AlertDialog.Builder(this).setTitle("修改测试主题")  
		    .setIcon(android.R.drawable.ic_dialog_info)  
		    .setView(et)  
		    .setPositiveButton("确定", new DialogInterface.OnClickListener() {  
		        

				public void onClick(DialogInterface dialog, int which) {  
		        input = et.getText().toString();  
		        if ("".equals(input)) {  
		            Toast.makeText(getApplicationContext(), "主题内容不能为空！" + input, Toast.LENGTH_LONG).show();  
		        }  
		        else {  
		        	OkHttpClient mOkHttpClient = new OkHttpClient();
		    		FormEncodingBuilder builder = new FormEncodingBuilder();
		    		builder.add("type", "34");
		    		builder.add("rowid", rowid);
		    		builder.add("c", account);
		    		builder.add("role", role);
		    		builder.add("tag", input);
		    		builder.add("status", "0");
		    		Request request = new Request.Builder()
		    				.url(Constant.SERVER_URL + "ManageMsg").post(builder.build())
		    				.build();
		    		mOkHttpClient.newCall(request).enqueue(new Callback() {
		    //http://192.168.0.198:8888/ycsj_platform/ManageMsg?type=33&c=13006314760&role=2&userclass=2722&tag=123&status=0
		    			@Override
		    			public void onFailure(Request arg0, IOException arg1) {
		    				runOnUiThread(new Runnable() {
		    					@Override
		    					public void run() {
		    						Toast.makeText(getBaseContext(), "网络无响应，请检查网络连接", 0)
		    								.show();
		    					}
		    				});
		    			}

		    			@Override
		    			public void onResponse(Response arg0) throws IOException {
		    				// 解析Json数据，保存登录状态及身份信息

		    				Gson gson = new Gson();
		    				String json = arg0.body().string();
		    				Log.e("test", json);
		    				
		    				AttResponse fromJson = gson.fromJson(json,
		    						AttResponse.class);

		    				if (fromJson != null) {
		    					if ("-1".equals(fromJson.state)
		    							|| "0".equals(fromJson.state)) {
		    						runOnUiThread(new Runnable() {
				    					@Override
				    					public void run() {
				    						Toast.makeText(getBaseContext(), "服务器开小差了，请重新添加", 0)
				    								.show();
				    					}
				    				});
		    					} else if ("1".equals(fromJson.state)) {
		    						
		    						runOnUiThread(new Runnable() {

										@Override
										public void run() {
											// TODO Auto-generated method stub
											Toast.makeText(getBaseContext(), "测试主题修改成功！", 0)
		    								.show();
											tv_title.setText(input);
										}
		    						});
		    					}
		    				}
		    			}
		    		});
		            }  
		        }
		        })  
		    .setNegativeButton("取消", null)  
		    .show();  
			
			
			break;
			
		}
	}

}
